import {addRule, removeRule, rule, updateRule} from '@/services/ant-design-pro/api';
import {PlusOutlined} from '@ant-design/icons';
import type {ActionType, ProColumns} from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import {FormattedMessage, useIntl} from '@umijs/max';
import {Button, Drawer, Input, message} from 'antd';
import React, {useRef, useState} from 'react';
import {
  addInterfaceInfoUsingPOST,
  deleteInterfaceInfoUsingPOST,
  listInterfaceInfoByPageUsingGET,
  offlineInterfaceInfoUsingPOST,
  onlineInterfaceInfoUsingPOST,
  updateInterfaceInfoUsingPOST
} from "@/services/tuzi-server/interfaceInfoController";
import {SortOrder} from "antd/lib/table/interface";
import CreateModal from "@/pages/Admin/InterfaceInfo/components/CreateModal";
import UpdateModal from "@/pages/Admin/InterfaceInfo/components/UpdateModal";

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.InterfaceInfo>();
  const [selectedRowsState, setSelectedRows] = useState<API.InterfaceInfo[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<API.InterfaceInfo>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index'
    },
    {
      title: (
        <FormattedMessage
          id="pages.interfaceInfo.list-user-id"
          defaultMessage="创建人"
        />
      ),
      dataIndex: 'userId',
      sorter: true,
      hideInForm: true,
      valueType: 'text'
    },
    {
      title: (
        <FormattedMessage
          id="pages.interfaceInfo.list-interface-name"
          defaultMessage="接口名称"
        />
      ),
      dataIndex: 'name',
      tip: '名称异常',
      valueType: 'text',
      formItemProps: {
        rules: [{
          required: true,
          message: 'Please enter'
        }

        ]
      }
    },
    {
      title: <FormattedMessage
        id="pages.interfaceInfo.list-request-header"
        defaultMessage="请求头"/>,
      dataIndex: 'requestHeader',
      valueType: 'jsonCode',
    },
    {
      title: (
        <FormattedMessage
          id="pages.interfaceInfo.list-response-header"
          defaultMessage="响应头"
        />
      ),
      dataIndex: 'responseHeader',
      sorter: true,
      valueType: 'jsonCode'
    },
    {
      title: (
        <FormattedMessage
          id="pages.interfaceInfo.list-url"
          defaultMessage="接口地址"
        />
      ),
      dataIndex: 'url',
      sorter: true,
      valueType: 'text'
    },
    {
      title: (
        <FormattedMessage
          id="pages.interfaceInfo.list-method"
          defaultMessage="请求类型"
        />
      ),
      dataIndex: 'method',
      sorter: true,
      valueType: 'text'
    },
    {
      title: (
        <FormattedMessage
          id="pages.interfaceInfo.list-params"
          defaultMessage="请求参数"
        />
      ),
      dataIndex: 'requestParams',
      sorter: true,
      valueType: 'jsonCode'
    },
    {
      title:
        <FormattedMessage
          id="pages.interfaceInfo.list-status"
          defaultMessage="状态"/>,
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: (
            <FormattedMessage
              id="pages.interfaceInfo.list-status-default"
              defaultMessage="关闭"
            />
          ),
          status: 'Default',
        },
        1: {
          text: (
            <FormattedMessage
              id="pages.interfaceInfo.list-status-open"
              defaultMessage="使用"/>
          ),
          status: 'Processing',
        },
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.interfaceInfo.list-description"
          defaultMessage="描述"
        />
      ),
      sorter: true,
      dataIndex: 'description',
      valueType: 'textarea',
    },
    {
      title: (
        <FormattedMessage
          id="pages.interfaceInfo.list-update-time"
          defaultMessage="更新时间"
        />
      ),
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInForm: true
    },
    {
      title: (
        <FormattedMessage
          id="pages.interfaceInfo.list-create-time"
          defaultMessage="创建时间"
        />
      ),
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInForm: true
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating"/>,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="update"
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record);
          }}
        >
          <FormattedMessage id="pages.interfaceInfo.option.update" defaultMessage="更新"/>
        </a>,

        record.status === 0 ? <Button
          key="online"
          danger
          onClick={() => {
            handleOnline(record);
            setCurrentRow(record);
          }}
        >
          <FormattedMessage id="pages.interfaceInfo.option.online" defaultMessage="发布"/>
        </Button> : null,
      /**
       * 这里可以直接使用三目运算符来对应的渲染按钮
       */
      record.status === 1 ?<Button
          key="offline"
          danger
          onClick={() => {
            handleOffline(record);
            setCurrentRow(record);
          }}
        >
          <FormattedMessage id="pages.interfaceInfo.option.offline" defaultMessage="下线"/>
        </Button> : null,

        <Button
          key="remove"
          danger
          onClick={() => {
            handleRemove(record);
            setCurrentRow(record);
          }}
        >
          <FormattedMessage id="pages.interfaceInfo.option.delete" defaultMessage="删除"/>
        </Button>,
      ],
    },
  ];

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.InterfaceInfo) => {
    const hide = message.loading('正在添加');
    try {
      await addInterfaceInfoUsingPOST({...fields});
      hide();
      message.success('Added successfully');
      handleModalOpen(false)
      return true;
    } catch (error: any) {
      hide();
      message.error('Adding failed, please try again!' + error.message);
      return false;
    }
    //自动刷新
    actionRef.current?.reload();
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.InterfaceInfo) => {
    //无值直接返回
    if (!currentRow) return;
    const hide = message.loading('Configuring');
    try {

      await updateInterfaceInfoUsingPOST({
        id: currentRow?.id, //这个是 直接传id到后端
        ...fields});
      hide();
      message.success('Configuration is successful');
      return true;
    } catch (error) {
      hide();
      message.error('Configuration failed, please try again!');
      return false;
    }
    //自动刷新
    actionRef.current?.reload();
  };

  /**
   *  Online node
   * @zh-CN 发布节点
   *
   * @param selectedRows
   */
  const handleOnline = async (record: API.IdRequest) => {
    const hide = message.loading('正在发布');
    if (!record) return true;
    try {
      await onlineInterfaceInfoUsingPOST({
        id: record.id
      });
      hide();
      //自动刷新
      actionRef.current?.reload();

      message.success('online successfully and will refresh soon');
      return true;
    } catch (error) {
      hide();
      message.error('online failed, please try again');
      return false;
    }
  };

  /**
   *  Offline node
   * @zh-CN 下线节点
   *
   * @param selectedRows
   */
  const handleOffline = async (record: API.IdRequest) => {
    const hide = message.loading('正在下线');
    if (!record) return true;
    try {
      await offlineInterfaceInfoUsingPOST({
        id: record.id
      });
      hide();
      //自动刷新
      actionRef.current?.reload();

      message.success('Offline successfully and will refresh soon');
      return true;
    } catch (error) {
      hide();
      message.error('Offline failed, please try again');
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (record: API.InterfaceInfo) => {
    const hide = message.loading('正在删除');
    if (!record) return true;
    try {
      await deleteInterfaceInfoUsingPOST({
        id: record.id
      });
      hide();
      //自动刷新
      actionRef.current?.reload();

      message.success('Deleted successfully and will refresh soon');
      return true;
    } catch (error) {
      hide();
      message.error('Delete failed, please try again');
      return false;
    }
  };

  return (
    <PageContainer>
      <ProTable<API.InterfaceInfo, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: 'Enquiry form',
        })}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined/> <FormattedMessage id="pages.searchTable.new" defaultMessage="New"/>
          </Button>,
        ]}
        request={async (params, sort: Record<string, SortOrder>,
                        filter: Record<string, React.ReactPropTypes[] | null>) => {

          const res: any = await listInterfaceInfoByPageUsingGET({
            ...params
          })

          if (res?.data) {
            return {
              data: res?.data.records || [],
              success: true,
              total: res?.data.total || 0
            }
          } else {
            return {
              data: [],
              success: false,
              total: 0
            }
          }

        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen"/>{' '}
              <a style={{fontWeight: 600}}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项"/>
              &nbsp;&nbsp;
              <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="Total number of service calls"
                />{' '}
                {selectedRowsState.reduce((pre, item) => pre + item.callNo!, 0)}{' '}
                <FormattedMessage id="pages.searchTable.tenThousand" defaultMessage="万"/>
              </span>
            </div>
          }
        >
          <Button type="primary">
            <FormattedMessage
              id="pages.searchTable.batchApproval"
              defaultMessage="Batch approval"
            />
          </Button>
        </FooterToolbar>
      )}
      {/* 这是一个注释 */}
      {/* columns 传入 行数据 */}
      {/* onCancel 取消时调用 handleModalOpen(false) */}
      {/* onSubmit 提交时调用 handleAdd(values) */}
      {/* visible 显示控件判断 createModalOpen */}
      <CreateModal columns={columns}
                   onCancel={() => {
                     handleModalOpen(false);
                   }}
                   onSubmit={(values) => {
                     handleAdd(values)
                   }}
                   visible={createModalOpen}/>

      <UpdateModal
        columns={columns}
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        visible={updateModalOpen}
        values={currentRow || {}}
      />

    </PageContainer>
  );
};

export default TableList;
